﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;

namespace Helpers
{
    public static class FileAndFolderProcessing
    {
        #region GetFiles (string Path)
        /// <summary>
        /// Gets all the files in the given folder path and all its subdirectories
        /// </summary>
        public static string[] GetFiles(string path)
        {
            ArrayList files = new ArrayList();
            getFiles(path, ref files);

            return (string[])files.ToArray(typeof(string));
        }
        private static void getFiles(string path, ref ArrayList files)
        {
            try
            {
                string[] folders = Directory.GetDirectories(path);
                for (int i = 0; i < folders.Length; i++)
                    getFiles(folders[i], ref files);


                string[] curFiles = Directory.GetFiles(path);
                files.AddRange(curFiles);
            }
            catch
            { }
        }
        #endregion

        #region GetFiles (string path, string[] searchPatterns, bool includeSubFolders) +1 overload
        /// <summary>
        /// Gets all the files in the given folder path and all its subdirectories.
        /// </summary>
        /// <param name="searchPatterns">search patterns (ie, "*.exe")</param>
        public static string[] GetFiles(string path, string[] searchPatterns, bool includeSubFolders)
        {
            ArrayList files = new ArrayList();
            if (includeSubFolders)
            {
                getFiles(path, searchPatterns, ref files);
            }
            else
            {
                try
                {
                    for (int i = 0; i < searchPatterns.Length; i++)
                    {
                        string[] curFiles = Directory.GetFiles(path, searchPatterns[i]);
                        files.AddRange(curFiles);
                    }
                }
                catch
                { }
            }
            return (string[])files.ToArray(typeof(string));
        }


        /// <summary>
        /// Gets all the files in the given folder path and all its subdirectories.
        /// </summary>
        /// <param name="searchPattern">A series of valid search patterns, separated
        /// by ";". For example "*.jpg;prog*.exe"</param>
        public static string[] GetFiles(string path, string searchPattern, bool includeSubFolders)
        {
            string[] patterns = searchPattern.Split(';');
            return GetFiles(path, patterns, includeSubFolders);
        }

        private static void getFiles(string path, string[] searchPattern, ref ArrayList files)
        {
            // Try to get the current directory's folders
            try
            {
                string[] folders = Directory.GetDirectories(path);
                for (int i = 0; i < folders.Length; i++)
                    getFiles(folders[i], searchPattern, ref files);


                for (int i = 0; i < searchPattern.Length; i++)
                {
                    string[] curFiles = Directory.GetFiles(path, searchPattern[i]);
                    files.AddRange(curFiles);
                }
            }
            catch
            { }
        }
        #endregion

        //extracting patch archive
//        public static void Extract(string file, string extractPath)
//        {
//            try
//            {
////                updateWorker.ReportProgress(0, LangRes.Get("ExtractingUpdates"));
//
//                var zip1 = ZipFile.Read(file);
//                var zipEntryCount = 0;
//                using (zip1)
//                {
//                    foreach (var e in zip1)
//                    {
//                        zipEntryCount += 1;
//
//                        var progressPercentage = (int)(((double)(zipEntryCount) / zip1.Entries.Count) * 100);
//
////                        updateWorker.ReportProgress(progressPercentage, LangRes.Get("ExtractingUpdates"));
//                        e.Extract(extractPath, ExtractExistingFileAction.OverwriteSilently);
//                    }
//                }
//            }
//            catch (Exception ex)
//            {
////                MessageBox.Show(ex.Message, LangRes.Get("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
//            }
//        }

        //recursive function for copying all files and directories

        public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
        {
            try
            {
                if (source != null && target != null)
                {
                    if (Directory.Exists(target.FullName) == false)
                    {
                        Directory.CreateDirectory(target.FullName);
                    }
                    var filesCount = 0;
                    var sourceFiles = source.GetFiles();

                    foreach (var fi in sourceFiles)
                    {
                        filesCount++;
//                        updateWorker.ReportProgress((int)(((double)(filesCount) / sourceFiles.Length) * 50),
//                                                    LangRes.Get("InstallingUpdate"));
                        fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
                    }
                    filesCount = 0;
                    var sourceDirs = source.GetDirectories();
                    foreach (var diSourceSubDir in sourceDirs)
                    {
                        filesCount++;
//                        updateWorker.ReportProgress((int)(((double)(filesCount) / sourceDirs.Length) * 50) + 50,
//                                                    LangRes.Get("InstallingUpdate"));
                        var nextTargetSubDir =
                            target.CreateSubdirectory(diSourceSubDir.Name);
                        CopyAll(diSourceSubDir, nextTargetSubDir);
                    }
                }
            }
            catch (Exception ex)
            {
//                MessageBox.Show(ex.Message, LangRes.Get("Error"), MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        public static string GetChecksum(string file)
        {
            using(var stream = new BufferedStream(File.OpenRead(file), 1200000))
            {
                var sha = new SHA1Managed();
                var checksum = sha.ComputeHash(stream);
                return BitConverter.ToString(checksum).Replace("-", String.Empty);
            }
        }

        public static void DeleteFile(string file)
        {
            try
            {
                File.Delete(file);
            }
            catch
            {
            }
        }
    }
}
